// packageLive/pages/cutPrice/list/list.js
var util = require('../../../../utils/util') //引入配置接口文件
import { spellApi, QRCode } from '../../../../config/config'
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    footprintGuid: '', //足迹全局id
    statusHeight: app.globalData.StatusBar,
    imgUrl: getApp().globalData.imgUrl,
    listData: [],
    page: 1,
    rows: 8,
    currentnomoreData: false,
    activityShareDlg: false,
    orderNowDlg: false,
    titleHeight: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    let that = this
    that.getcutPriceList()
    wx.getSystemInfo({
      success(res) {
        let statusBarHeight = res.statusBarHeight + 65
        let listMargintop = res.statusBarHeight + 65 + 59
        that.setData({
          titleHeight: statusBarHeight + 'px',
          listMargintop: listMargintop + 'px'
        })
      }
    })
  },
  goreBack: function (e) { //返回
    wx.navigateBack({
      delta: 1
    })
  },
  getcutPriceList() {
    let that = this
    let parms = {
      "page": that.data.page,
      "rows": that.data.rows
    }
    app.reqFun.requestJson('POST',spellApi.cutPriceList,parms,(res)=>{
      if(res.data.success === 1) {
        let records = res.data.data.records
        if (records.length < that.data.rows) {
          that.setData({
            currentnomoreData: true
          })
        }
        that.setData({
          listData: that.data.listData.concat(records)
        })
      }
    })
  },
  // 去砍价详情
  goDetail(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/packageLive/pages/cutPrice/detail/detail?id=' + id,
    })
  },
  gobuyDlg(e) {
    let item = e.currentTarget.dataset.item
    this.setData({
      orderNowDlg: true,
      item: item
    })
  },
  stopBargain() {
    let cutPriceGroupId = this.data.item.id
    app.reqFun.requestJson('GET',spellApi.halfwayBuy + cutPriceGroupId,'',(res)=>{
      if(res.data.success === 1) {
        this.gobuyGoods()
      }
    })
  },
  gobuyGoods() { // 立即购买
    var sku = this.data.item
    var skus = [{
      skuId: sku.skuId,
      number: sku.buyNum
    }]
    var submitdata = {
      sku: skus
    }
    submitdata.omsOrderType = 'CUT_PRICE',
    submitdata.settlementMethod = "BUY_NOW"
    submitdata.groupActivityId = sku.cutActivityId
    if (sku.id) {
      submitdata.groupId = sku.id
    }
    wx.setStorageSync('submitSku', submitdata)
    wx.navigateTo({
      url: '/packagBuy/pages/confirmOrder/confirmOrder?type=orderOnline',
    })
  },
  cutbuyGoods(e) { // 砍价下单
    var sku = e.currentTarget.dataset.item
    var skus = [{
      skuId: sku.skuId,
      number: sku.buyNum
    }]
    var submitdata = {
      sku: skus
    }
    submitdata.omsOrderType = 'CUT_PRICE',
    submitdata.settlementMethod = "BUY_NOW"
    submitdata.groupActivityId = sku.cutActivityId
    if (sku.id) {
      submitdata.groupId = sku.id
    }
    wx.setStorageSync('submitSku', submitdata)
    wx.navigateTo({
      url: '/packagBuy/pages/confirmOrder/confirmOrder?type=orderOnline',
    })
  },
  activityShareClose() {
    this.setData({ activityShareDlg: false })
  },
  // goShare(e) {
  //   let that = this
  //   let userInfo = wx.getStorageSync('loginMsg').userInfo
  //   let partnerPhoto =  userInfo.icon
  //   let item = e.currentTarget.dataset.item
  //   let cutGoodsPicture = that.data.imgUrl + item.cutGoodsPicture
  //   let id = item.id
  //   //砍价成功通知订阅
  //   app.cutPriceNotifySubscribe(()=>{
  //     wx.getImageInfo({
  //       src:  cutGoodsPicture,
  //       success: function (res) {
  //         that.setData({
  //           goodsImgUrl: res.path
  //         })
  //       }
  //     })
  //     wx.getImageInfo({
  //       src:  partnerPhoto,
  //       success: function (res) {
  //         that.setData({
  //           headerImgUser: res.path
  //         })
  //       }
  //     })
  //     that.setData({
  //       userInfo: userInfo,
  //       detailData: item,
  //       activityShareDlg: true,
  //       id: id
  //     })
  //     that.getQrcode(item.id, item.cutActivityId)
  //   }, id)
  // },
  // 获取小程序码
  getQrcode(cutGroupId, cutActivityId) {
    var that = this;
    var userId = wx.getStorageSync('loginMsg').userId
    let path = `packageLive/pages/cutPrice/detail/detail`
    var parms = {
      page: path,
      scene: JSON.stringify({
        userId: userId,
        id: cutGroupId
      })
    }
    // 保存分享记录
    app.insertShareRecord(path, null, cutActivityId, 'cutPrice', userId)
    app.reqFun.requestJson('POST', QRCode, parms, (res) => {
      if (res.data.success == 1) {
        that.setData({
          shearImg: 'data:image/png;base64,' + res.data.data,
          modelPopup: 'shear-pop-download'
        })
        that.send_code('data:image/png;base64,' + res.data.data)
        console.log('shearImg', that.data.shearImg)
      }
    })
  },
  send_code(code) { //base64图片转本地缓存图片
    var that = this;
    const fs = wx.getFileSystemManager();
    //随机定义路径名称
    var times = new Date().getTime();
    var codeimg = wx.env.USER_DATA_PATH + '/' + times + '.png';
    //将base64图片写入
    fs.writeFile({
      filePath: codeimg,
      data: code.slice(22),
      encoding: 'base64',
      success: () => {
        //写入成功了的话，新的图片路径就能用了
        that.setData({
          codeImg: codeimg
        })
      }
    });
  },
  //分享商品海报
  // downloadCanvas: function (e) {
  //   let that = this
  //   app.getLogin((re)=>{
  //     if(re){
  //       wx.showLoading({
  //         title: '图片生成中···',
  //       })
  //       var userInfo = that.data.userInfo
  //       var headerImgUser = that.data.headerImgUser
  //       var headerNameUser = userInfo.nickname
  //       var detailData = that.data.detailData
  //       var goodsImgUrl = that.data.goodsImgUrl 
  //       var codeImg = that.data.codeImg
  //       // 
  //       const ctx = wx.createCanvasContext('shareGoods')

  //       ctx.save();
  //       ctx.beginPath()     //头像绘制
  //       ctx.setFillStyle('#fff')
  //       ctx.fillRect(0, 0, 300, 322)
  //       ctx.arc(30, 25, 20, 0, 2*Math.PI)
  //       ctx.clip()
  //       ctx.drawImage(headerImgUser, 10, 5, 40, 40)
  //       ctx.restore()
  //       ctx.beginPath()
  //       ctx.setFillStyle('#333')
  //       ctx.font = "bold 13px Arial"
  //       var nickNameWidth = ctx.measureText(headerNameUser).width
  //       ctx.fillText(headerNameUser, 65,20, nickNameWidth)
  //       ctx.fillText('向您推荐',65+nickNameWidth+20,20)
  //       ctx.setFillStyle('#888')
  //       ctx.font = "200 12px Arial"
  //       ctx.fillText('发现一件好物,来帮我砍价拿吧',65,40)

  //       ctx.beginPath() // 商品信息
  //       ctx.fillStyle = '#F4F6F5'
  //       ctx.fillRect(10, 60, 280, 130)
 
  //       ctx.beginPath()
  //       ctx.drawImage(goodsImgUrl, 20, 70, 110, 110)

  //       ctx.beginPath()
  //       ctx.setFillStyle('#333')
  //       ctx.font = "bold 14px Arial"
  //       // ctx.fillText(detailData.cutGoodsName, 140,90, 135)
  //       var name = detailData.cutGoodsName //插入商品名称
  //       var txtWidth = ctx.measureText(name).width
  //       var textToHeight = 90
  //       if (txtWidth < 135) {
  //         ctx.fillText(name, 140, textToHeight + 5)
  //         textToHeight = textToHeight + 20
  //       } else { //处理插入商品名称过长
  //         var row = []
  //         var n = Math.ceil(135 / 16)
  //         for (var i = 0, l = name.length; i < l / n; i++) {
  //           var a = name.slice(n * i, n * (i + 1));
  //           row.push(a);
  //         }
  //         for (var b = 0; b < row.length; b++) {
  //           ctx.fillText(row[b], 140, textToHeight)
  //           textToHeight = textToHeight + 20
  //         }
  //       }
  //       ctx.setFillStyle('#F15643')
  //       ctx.font = "bold 12px Arial"
  //       ctx.fillText('砍后最低价 ¥'+detailData.cutMiniPrice, 140,textToHeight+20, 135)
  //       ctx.setFillStyle('#999999')
  //       ctx.font = "12px Arial"
  //       ctx.fillText('¥'+detailData.originalPrice, 140,textToHeight+40, 135)

  //       ctx.beginPath()     //小程序码
  //       ctx.drawImage(codeImg, 50, 200, 80, 80)
  //       ctx.restore()

  //       ctx.beginPath()
  //       ctx.font = "12px Arial"
  //       ctx.setFillStyle('#888888')
  //       ctx.fillText('长按识别小程序码', 140,230)
  //       ctx.beginPath()
  //       ctx.font = "12px Arial"
  //       ctx.setFillStyle('#888888')
  //       ctx.fillText('轻松帮好友砍价', 140,250)
  //       ctx.draw()
  //       setTimeout(function () {
  //         wx.canvasToTempFilePath({ //canvas生成图片
  //           x: 0,
  //           y: 0,
  //           width: 300,
  //           height: 322,
  //           canvasId: 'shareGoods',
  //           success(res) {
  //             console.log(res.tempFilePath)
  //             wx.saveImageToPhotosAlbum({     //保存图片到相册
  //               filePath:res.tempFilePath,
  //               success:function(e){
  //                 wx.hideLoading({})
  //                 wx.showToast({
  //                   title: '保存图片成功',
  //                   duration:3000
  //                 })
  //               },fail:function(e){
  //                 wx.hideLoading({})
  //                 wx.showModal({
  //                   title: '保存失败',
  //                   content: '保存图片失败,请点击右上角按钮-设置-开启授权',
  //                   showCancel:false,
  //                 })
  //               }
  //             })
  //           }
  //         })
  //       }, 4000)
  //     } else {
  //       if (wx.getUserProfile) {
  //         app.getUserProfile(function(){
  //           that.setData({
  //             getPhoneNumberData:{
  //               isShowGetPhoneNumber:true
  //             }
  //           })
  //         })
  //       } else {
  //         if(!wx.getStorageSync('loginMsg').bindingPhone){
  //           that.setData({
  //             getPhoneNumberData:{
  //               isShowGetPhoneNumber:true
  //             }
  //           })
  //         } else {
  //           callback(true)  //低版本微信绑过电话视为已登录
  //         }
  //       }
  //     }
  //   })
  // },
  orderNowClose() {
    this.setData({
      orderNowDlg: false,
      page: 1,
      rows: 8,
    })
    that.getcutPriceList()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      footprintGuid: util.guid()
    })
    //保存访问足迹
    app.saveAccessFootprint(this.data.footprintGuid, 'myCutPrice', null)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.currentnomoreData) {
      this.setData({
        page: this.data.page + 1
      })
      this.getcutPriceList()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    // var that=this
    // that.activityShareClose()
    // var id = that.data.id //商品id
    // // var userId = wx.getStorageSync('loginMsg').userId
    // var cutGoodsName = that.data.detailData.cutGoodsName
    // let url = `/packageLive/pages/cutPrice/detail/detail?id=${id}`
    // return {
    //   title: cutGoodsName,
    //   path: url
    // }
  }
})